package com.junjiao.util.web;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.junjiao.util.java.StringUtil;

/**
 * @author wanggz
 * 
 */
public class MobileClientTools {

	final static String CHAR_SET = "utf-8";
	final static Log log = LogFactory.getLog(MobileClientTools.class);

	/**
	 * 设置请求信息
	 * 
	 * @param method
	 * @param action
	 */
	private static void setMothed(final HttpMethod method, String action,
			String telNumber, String userId) {

		method.setRequestHeader("Action", action);
		method.setRequestHeader("Client-Agent", MobileConfig.clientAgent);
		method.setRequestHeader("ClientVersion", MobileConfig.ClientVersion);
		method.setRequestHeader("APIVersion", "1.0.0.0");

		if (!"".equals(StringUtil.nullToStr(userId))) {
			method.setRequestHeader("user-id", userId);
		} else {
			method.setRequestHeader("user-id", MobileConfig.userId);
		}

		if (!"".equals(StringUtil.nullToStr(telNumber))) {
			method.setRequestHeader("x-up-calling-line-id", telNumber);
		} else {
			method.setRequestHeader("x-up-calling-line-id",
					MobileConfig.telNunmber);
		}
		/*
		 * method.setRequestHeader("user-id", "111122233444");
		 * method.setRequestHeader("x-up-calling-line-id", "13316099335");
		 */
	}

	/**
	 * 设置请求信息
	 * 
	 * @param method
	 * @param action
	 */
	public static void setMothed(final HttpMethod method, String action) {

		method.setRequestHeader("Action", action);
		method.setRequestHeader("Client-Agent", MobileConfig.clientAgent);
		method.setRequestHeader("ClientVersion", MobileConfig.ClientVersion);
		method.setRequestHeader("APIVersion", "1.0.0.0");
		method.setRequestHeader("user-id", MobileConfig.userId);
		method
				.setRequestHeader("x-up-calling-line-id",
						MobileConfig.telNunmber);
		/*
		 * method.setRequestHeader("user-id", "111122233444");
		 * method.setRequestHeader("x-up-calling-line-id", "13316099335");
		 */
	}

	/**
	 * 返回xml文件
	 * 
	 * @param action
	 * @param param
	 * @param encoder
	 * @return
	 */
	public static String doPostMothod(String action, String param,
			boolean encoder) {

		InputStream is = null;
		StringBuffer buffer = new StringBuffer("");
		InputStreamReader input = null;
		PostMethod post = null;
		String code = "";

		try {

			if (encoder) {
				param = URLEncoder.encode(param, CHAR_SET);
			}
			String url = MobileConfig.mobileURL.substring(0,
					MobileConfig.mobileURL.length() - 1);

			HttpClient client = HttpClientTools.getClient();
			post = new PostMethod(url);
			MobileClientTools.setMothed(post, action);

			StringRequestEntity strRe = new StringRequestEntity(param,
					"application/xml", CHAR_SET);
			post.setRequestEntity(strRe);

			client.executeMethod(post);

			int a = 0;
			if (post.getStatusCode() == 200) {

				if ("0"
						.equals(post.getResponseHeader("result-code")
								.getValue())) {

					input = new InputStreamReader(post
							.getResponseBodyAsStream(), CHAR_SET);
					while ((a = input.read()) != -1) {
						buffer.append((char) a);
					}

				} else {
					log.warn("error: network error, errorcode "
							+ post.getStatusCode());
					log.warn("error: result-code "
							+ post.getResponseHeader("result-code"));
				}
			} else {
				log.warn("error: network error, errorcode "
						+ post.getStatusCode());
				log.warn("error: result-code "
						+ post.getResponseHeader("result-code"));
			}

			code = post.getResponseHeader("result-code").getValue();
			if ("".equals(buffer.toString())) {
				return code;
			}

			return buffer.toString();

		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			try {
				if (is != null) {
					is.close();
					is = null;
				}

				if (post != null) {
					post.releaseConnection();
					post = null;
				}

			} catch (Exception e) {

			}
		}
		return "";
	}

	/**
	 * 返回xml文件
	 * 
	 * @param action
	 * @param param
	 * @param encoder
	 * @return
	 */
	public static String doPostMothod(String action, String param,
			boolean encoder, String telNumber, String userId) {

		InputStream is = null;
		StringBuffer buffer = new StringBuffer("");
		InputStreamReader input = null;
		PostMethod post = null;
		String code = "";

		try {

			if (encoder) {
				param = URLEncoder.encode(param, CHAR_SET);
			}
			String url = MobileConfig.mobileURL.substring(0,
					MobileConfig.mobileURL.length() - 1);

			HttpClient client = HttpClientTools.getClient();
			post = new PostMethod(url);
			MobileClientTools.setMothed(post, action, telNumber, userId);

			StringRequestEntity strRe = new StringRequestEntity(param,
					"application/xml", CHAR_SET);
			post.setRequestEntity(strRe);

			client.executeMethod(post);

			int a = 0;
			if (post.getStatusCode() == 200) {

				if ("0"
						.equals(post.getResponseHeader("result-code")
								.getValue())) {

					input = new InputStreamReader(post
							.getResponseBodyAsStream(), CHAR_SET);
					while ((a = input.read()) != -1) {
						buffer.append((char) a);
					}

				} else {
					log.warn("error: network error, errorcode "
							+ post.getStatusCode());
					log.warn("error: result-code "
							+ post.getResponseHeader("result-code"));
					return "";
				}
			} else {
				log.warn("error: network error, errorcode "
						+ post.getStatusCode());
				log.warn("error: result-code "
						+ post.getResponseHeader("result-code"));
				return "";
			}

			code = post.getResponseHeader("result-code").getValue();
			if ("".equals(buffer.toString())) {
				return code;
			}
			return buffer.toString();

		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			try {
				if (is != null) {
					is.close();
					is = null;
				}

				if (post != null) {
					post.releaseConnection();
					post = null;
				}

			} catch (Exception e) {

			}
		}
		return "";
	}

	/**
	 * 返回状态码 0 表成功 非0 失败
	 * 
	 * @param action
	 * @param param
	 * @param encoder
	 * @return
	 */
	public static String doPostMothodResultCode(String action, String param,
			boolean encoder) {

		PostMethod post = null;

		try {

			if (encoder) {
				param = URLEncoder.encode(param, CHAR_SET);
			}
			String url = MobileConfig.mobileURL.substring(0,
					MobileConfig.mobileURL.length() - 1);

			HttpClient client = HttpClientTools.getClient();
			post = new PostMethod(url);
			MobileClientTools.setMothed(post, action);

			StringRequestEntity strRe = new StringRequestEntity(param,
					"application/xml", CHAR_SET);
			post.setRequestEntity(strRe);

			client.executeMethod(post);

			if (post.getStatusCode() == 200) {

				if ("0"
						.equals(post.getResponseHeader("result-code")
								.getValue())) {

					log.warn("error: network error, errorcode "
							+ post.getStatusCode());
					log.warn("error: result-code "
							+ post.getResponseHeader("result-code").getValue());
				}
			}

			return post.getResponseHeader("result-code").getValue();

		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			try {
				if (post != null) {
					post.releaseConnection();
					post = null;
				}

			} catch (Exception e) {

			}

		}
		return "";

	}

	/**
	 * 返回xml文件
	 * 
	 * @param action
	 * @param param
	 * @param encoder
	 * @return
	 */
	public static String doGetMothod(String action, String param,
			boolean encoder) {

		StringBuffer buffer = new StringBuffer("");
		GetMethod get = null;
		InputStreamReader input = null;
		String code = "";

		try {

			if (encoder) {
				param = java.net.URLEncoder.encode(param, CHAR_SET);
			}

			HttpClient client = HttpClientTools.getClient();
			get = new GetMethod(MobileConfig.mobileURL + param);

			MobileClientTools.setMothed(get, action);
			client.executeMethod(get);

			int a = 0;
			if (get.getStatusCode() == 200) {

				if ("0".equals(get.getResponseHeader("result-code").getValue())) {

					input = new InputStreamReader(
							get.getResponseBodyAsStream(), CHAR_SET);
					while ((a = input.read()) != -1) {
						buffer.append((char) a);
					}

				} else {
					log.warn("error: network error, errorcode "
							+ get.getStatusCode());
					log.warn("error: result-code "
							+ get.getResponseHeader("result-code"));

				}
			} else {
				log.warn("error: network error, errorcode "
						+ get.getStatusCode());
				log.warn("error: result-code "
						+ get.getResponseHeader("result-code"));

			}

			if (log.isDebugEnabled()) {
				log.info(get.getResponseHeader("result-code"));
				log.info(get.getStatusCode());
			}

			code = get.getResponseHeader("result-code").getValue();

		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			try {
				if (input != null) {
					input.close();
					input = null;
				}
				if (get != null) {
					get.releaseConnection();
					get = null;
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if ("".equals(buffer.toString())) {
			return code;
		}

		return buffer.toString();
	}

	/**
	 * 返回状态码 0 表成功 非0 失败
	 * 
	 * @param action
	 * @param param
	 * @param encoder
	 * @return
	 */
	public static String doGetMothodResultCode(String action, String param,
			boolean encoder) {

		GetMethod get = null;

		try {

			if (encoder) {
				param = java.net.URLEncoder.encode(param, CHAR_SET);
			}

			HttpClient client = HttpClientTools.getClient();
			get = new GetMethod(MobileConfig.mobileURL + param);

			MobileClientTools.setMothed(get, action);
			client.executeMethod(get);

			if (get.getStatusCode() == 200) {

				log.warn("error: network error, errorcode "
						+ get.getStatusCode());
				log.warn("error: result-code "
						+ get.getResponseHeader("result-code").getValue());

				if (log.isDebugEnabled()) {
					log.info(get.getResponseHeader("result-code"));
					log.info(get.getStatusCode());
				}
			}

			return get.getResponseHeader("result-code").getValue();

		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			try {
				if (get != null) {
					get.releaseConnection();
					get = null;
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return "";
	}

	public static void downLoad(String action, String mobileURL) {

		// String mobileURL =
		// "http://61.130.247.175:8080/portalapi/download?key=downloadContent10000027674644type1";
		StringBuffer buffer = new StringBuffer("");
		GetMethod get = null;
		InputStreamReader input = null;

		try {

			HttpClient client = HttpClientTools.getClient();
			get = new GetMethod(mobileURL);

			MobileClientTools.setMothed(get, action);
			client.executeMethod(get);

			int a = 0;
			if (get.getStatusCode() == 200) {

				// if("0".equals(StringUtil.nullToStr(get.getResponseHeader("result-code").getValue()))){

				System.out.println(get.getResponseCharSet());
				input = new InputStreamReader(get.getResponseBodyAsStream(),
						"utf-8");

				FileOutputStream out = new FileOutputStream("file.txt");
				while ((a = input.read()) != -1) {
					out.write(a);
				}
				out.flush();
				out.close();
				input.close();
				/*
				 * }else{ log.warn("error: network error, errorcode " +
				 * get.getStatusCode()); log.warn("error: result-code " +
				 * get.getResponseHeader("result-code")); }
				 */
			} else {
				log.warn("error: network error, errorcode "
						+ get.getStatusCode());
				log.warn("error: result-code "
						+ get.getResponseHeader("result-code"));
			}

			if (log.isDebugEnabled()) {
				log.info(get.getResponseHeader("result-code"));
				log.info(get.getStatusCode());
			}

		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			try {
				if (input != null) {
					input.close();
					input = null;
				}
				if (get != null) {
					get.releaseConnection();
					get = null;
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static void downLoadSimple(String action, String mobileURL) {

		// String mobileURL =
		// "http://61.130.247.175:8080/portalapi/download?key=downloadContent10000027674644type1";
		StringBuffer buffer = new StringBuffer("");
		GetMethod get = null;
		InputStreamReader input = null;

		try {

			HttpClient client = HttpClientTools.getClient();
			get = new GetMethod(mobileURL);

			MobileClientTools.setMothed(get, action);
			client.executeMethod(get);

			int a = 0;
			if (get.getStatusCode() == 200) {

				// if("0".equals(StringUtil.nullToStr(get.getResponseHeader("result-code").getValue()))){

				System.out.println(get.getResponseCharSet());
				input = new InputStreamReader(get.getResponseBodyAsStream(),
						"gb2312");

				FileOutputStream out = new FileOutputStream("/file.zip");
				while ((a = input.read()) != -1) {
					out.write(a);
				}
				out.flush();
				out.close();
				input.close();
				/*
				 * }else{ log.warn("error: network error, errorcode " +
				 * get.getStatusCode()); log.warn("error: result-code " +
				 * get.getResponseHeader("result-code")); }
				 */
			} else {
				log.warn("error: network error, errorcode "
						+ get.getStatusCode());
				log.warn("error: result-code "
						+ get.getResponseHeader("result-code"));
			}

			if (log.isDebugEnabled()) {
				log.info(get.getResponseHeader("result-code"));
				log.info(get.getStatusCode());
			}

		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			try {
				if (input != null) {
					input.close();
					input = null;
				}
				if (get != null) {
					get.releaseConnection();
					get = null;
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
